let myApp = getApp()
let tip = {
  1: '抱歉，出现错误',
  1005: 'appkey无效, 请联系管理员！',
  3000: '数据不存在'
}

class HTTP {
  constructor() {
    this.baseUrl = myApp.globalData.baseUrl
    this.appkey = myApp.globalData.appkey
  }
  //promise改写回调
  request({ url, data = {}, method = "GET" }) {
    return new Promise((resolve, reject) => {
      let newUrl = this.baseUrl + url
      wx.request({
        url: newUrl,
        data: data,
        method: method,
        header: {
          'content-type': 'application/json', // 默认值
          appkey: this.appkey,
        },
        success: res => {
          let code = res.statusCode.toString()
          if (code.startsWith('2')) {
            resolve(res.data)
          }else {
            reject()
            let errorCode = res.data.error_code || res.statusCode || 1
            this._errorMsg(errorCode)
          }
        },
        fail: err => {
          reject()
          this._errorMsg(1)
        }
      })
    })
  }

  //公用错误提示
  _errorMsg(msg) {
    if (!msg) msg = 1
    let tips = tip[msg] ? tip[msg] : tip[1]
    wx.showToast({
      title: tips,
      icon: 'none',
      duration: 2000
    })
  }
}

export {
  HTTP
}